import utils from '../../utils/util';
import WxValidate from '../../utils/WxValidate';
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    opts: "",
    systemInfo: "",
    phoneNumber: "", //用户输入的手机号码
    isPhoneNumberRight: false, //手机号码是否正确
    codeTime: 60, //验证码倒计时
    shopList:[], //店铺列表
    // isCheckUserIdDialogShow: false, //查找用户id弹框是否显示
    isShowPhonePopup: false, //
    // isShowShopPopup:false, //
    // isChooseAgreement: false, //协议是否选中
    // isShowUserAgreementDialog: false, //用户协议
    // userAgreementIntro: '',
    // privacyAgreementIntro: '',
    // isShowPrivacyAgreementDialog: false, //隐私协议
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    let systemInfo = utils.getStorage("systemInfo");
    this.setData({
      systemInfo: systemInfo
    });
    utils.asyncLogin().then(res => {
      this._userSecret = res;
    });

    this._fromOpenerData = {};

    //获取上一页传递过来的额数据
    this._getAcceptDataFromOpenerPage().then((data) => {
      /**
       * uri:"重哪个页面跳转过来的url"
       * options:参数
       */
      console.log("_getAcceptDataFromOpenerPage", data);
      this._fromOpenerData = data;
      this.setData({
        opts: data.options
      })
    });
  },
  toggleCheck() {
    this.setData({
      isChooseAgreement: !this.data.isChooseAgreement
    })
  },
  chooseShop(e){
    let item=e.currentTarget.dataset.item;
    utils.post('appletLive/companyLogin',{companyId:item.companyId,userId:item.userId}).then(res=>{
      utils.setStorage("token",res.token).then(()=>{
        this._jumpPage();
      });
   })
  },
  //其他的登录弹框打开
  openPhonePopup() {
    this.setData({
      isShowPhonePopup: true
    })

  },
  //其他的登录弹框关闭
  onOtherLoginClose() {
    this.setData({
      isOtherLoginShow: false
    })
  },
  //手机验证
  goAuthPhone: function () {
    this.onOtherLoginClose();
    this.setData({
      step: 2,
    }, () => {
      this._initValidate()
    })
  },
  //用户id验证
  goAuthUserID: function () {
    this.onOtherLoginClose();
    this.setData({
      step: 3
    }, () => {
      this._initValidate()
    })
  },
  //步骤切换
  onSwitchStep: function () {
    wx.navigateBack()
  },
  goBackFirstStep() {
    this.setData({
      step: 1
    })
  },



  //获取手机号码
  getPhoneNumber: function (e) {
    let flag = false;
    let phoneNumber = e.detail.value;
    if (/^1[3456789]\d{9}$/.test(phoneNumber)) {
      flag = true;
    }
    this.setData({
      phoneNumber: phoneNumber,
      isPhoneNumberRight: flag
    })
  },
  //获取手机验证码
  getPhoneCode: function () {
    if (this.phoneNumerTimer !== null) {
      clearTimeout(this.phoneNumerTimer);
    }
    this.phoneNumerTimer = setTimeout(() => {
      utils.post('liveApplet/sendSmsCode', {
        openId:this._userSecret.openId,
        mobile: this.data.phoneNumber
      }).then(() => {
        wx.showToast({
          title: '验证码将在10分钟内有效！',
          icon:"none"
        })
        this._phoneCodeCountdown();
      })
    }, 1000);

  },
  //手动输入手机号码验证
  formSubmitPhone: function (e) {
    let params = e.detail.value;
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0];
      wx.showToast({
        title: error.msg,
        icon:"none",
        duration:2500
      })
    } else {
      utils.post('liveApplet/mobileLogin', {
        ...params,
        openId: this._userSecret.openId,
      }).then((res) => {
        if(res.loginToken){
          utils.setStorage("token", res.loginToken);
          utils.setStorage("shopInfo", res.companyInfo);
          this._jumpPage()
        }else{
          wx.showToast({
            title: "未找到对应的店铺",
            icon:"none"
          })
        }
      }).catch((res) => {
        let msg = res.data.msg || '服务器繁忙，请稍后重试！';
        wx.showToast({
          title: msg,
          icon:"none"
        })
      });
    }
  },
  //微信一键授权手机验证码
  bindGetphonenumber: function (e) {
    if (e.detail.errMsg.indexOf("deny") === -1) {
      utils.post('liveApplet/authMobileLogin', {
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv,
        sessionKey: this._userSecret.sessionKey,
        openId: this._userSecret.openId,
      }).then(res => {
        if (res.loginToken) {
          utils.setStorage("token", res.loginToken);
        }
        if (res.companyInfo) {
          utils.setStorage("shopInfo", res.companyInfo);
        }
        this._jumpPage();
      }).catch((res) => {
        let msg = res.data.msg || '服务器繁忙，请稍后重试！';
        wx.showToast({
          title: msg
        });
      });
    }
  },


  //用户id的验证
  formUserIdSubmit: function (e) {
    let params = e.detail.value;
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0];
      utils.showMyToast(error.msg, 'error');
    } else {
      utils.wxRequestPost('appletLive/userIdBind', {
        userId: e.detail.value.userId,
        liveId: this.fromOpenerData.options.liveId,
        openId: this.wxUK.openId,
        role: this.fromOpenerData.options.role, //授权的时候需要区分讲师还是学员，1讲师(该页面认为是) 2学员(连麦页面是学员)
        moduleType: this.fromOpenerData.options.mt * 1 || 1,
      }).then(res => {
        if (res.token) {
          app.setStorage("token", res.token).then(res => {
            this._jumpPage();
          });
        } else {
          wx.navigateTo({
            url: `/pages/checkResult/index?liveId=${this.fromOpenerData.options.liveId || ''}&role=${this.fromOpenerData.options.role || 1}`,
          })
        }
      });
      log.info({
        type: "formUserIdSubmit",
        intro: "用户id登录",
        liveId: this.fromOpenerData.options.liveId,
        userId: e.detail.value.userId,
        userInfo: app.getStorage("userInfo"),
        fromOpenerData: this.fromOpenerData
      })
    }
  },
  //找用户id弹框提示
  openCheckUserIdDialog: function () {
    this.setData({
      isCheckUserIdDialogShow: true
    });
  },
  openUserAgreement() {
    if (!this.data.userAgreementIntro) {
      this._getAgreement(64).then((res) => {
        this.setData({
          userAgreementIntro: res,
          isShowUserAgreementDialog: true
        });
      })
    } else {
      this.setData({
        isShowUserAgreementDialog: true
      });
    }
  },
  openPrivacyAgreement() {
    if (!this.data.privacyAgreementIntro) {
      this._getAgreement(65).then((res) => {
        this.setData({
          privacyAgreementIntro: res,
          isShowPrivacyAgreementDialog: true
        });
      })
    } else {
      this.setData({
        isShowPrivacyAgreementDialog: true
      });
    }

  },
  _getAgreement(id) {
    return new Promise((resolve) => {
      utils.wxRequestGet(`appletLive/getServiceAgreement/${id}`, {}, true).then(res => {
        resolve(res.content);
      })
    })

  },
  phoneFormOpen() {
    this._initValidate();
  },
  //初始化验证规则
  _initValidate: function () {
    let rules = {
      mobile: {
        required: true,
        tel: true
      },
      code: {
        required: true
      }
    };
    let messages = {
      mobile: {
        required: "请输入手机号码",
        tel: "请输入正确手机号码"
      },
      code: {
        required: "请输入验证码",
      }
    }
    this.WxValidate = new WxValidate(rules, messages);
  },
  //获取验证码倒计时
  _phoneCodeCountdown: function () {
    this.codeTimer = setInterval(() => {
      this.setData({
        codeTime: this.data.codeTime - 1
      });
      if (this.data.codeTime < 1) {
        clearInterval(this.codeTimer);
        this.setData({
          codeTime: 60,
          isPhoneNumberRight: true,
          isRunning: false,
        });

      };
    }, 1000)
  },
  //接收跳转页面传递的数据
  _getAcceptDataFromOpenerPage: function () {
    return new Promise((resolve, reject) => {
      const eventChannel = this.getOpenerEventChannel();
      if (Object.keys(eventChannel).length) {
        eventChannel.on('acceptDataFromOpenerPage', function (data) {
          data.options = data.options || {}
          resolve(data);
        })
      } else {
        resolve({
          options: {}
        });
      }
    })
  },
  //跳转函数(根据参数跳转不同的页面)
  _jumpPage: function (data = this._fromOpenerData) {
    let optionStr = "";
    Object.keys(data.options).forEach((key, index) => {
      optionStr += key + "=" + data.options[key] + "&";
    });
    optionStr = optionStr ? '?' + optionStr.substring(0, optionStr.length - 1) : '';
    console.log("_jumpPage", this._fromOpenerData)
    wx.reLaunch({
      url: this._fromOpenerData.uri ? (this._fromOpenerData.uri + optionStr) : '/pages/index/index'
    })
  },
})